package com.csdj.common.utils;

import okhttp3.*;

import java.io.IOException;
import java.util.Map;

public class HttpUtil {

    private static  OkHttpClient client = new OkHttpClient();

    public static String get(String url){
        final Request build = new Request.Builder().url(url).build();
        try {
            final Response response = client.newCall(build).execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String post(String url,Map<String,String> params) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),formatParameterForForm(params));
        final Request post = new Request.Builder().url(url).post(requestBody).build();
        try {
            final Response res = client.newCall(post).execute();
            return res.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     *
     * @param url
     * @param json
     * @return
     */
    public static String postJson(String url,String json){
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),json);
        final Request post = new Request.Builder().url(url).post(requestBody).build();
        try {
            final Response res = client.newCall(post).execute();
            return res.body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    private static String formatParameterForForm(Map<String,String> params){
        if(params != null && params.size()>0){
            StringBuilder sb = new StringBuilder();
            params.entrySet().stream().forEach(entry ->{
                sb.append(entry.getKey()+"="+entry.getValue()+"&");
            });
            return sb.substring(0,sb.length()-1);
        }
        return null;
    }
}
